#!/bin/bash

# 本地版本文件测试脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 测试版本文件格式
test_version_file() {
    local file=$1
    local client_name=$2

    print_info "测试 $client_name 版本文件: $file"

    if [[ ! -f "$file" ]]; then
        print_error "文件不存在: $file"
        return 1
    fi

    # 验证JSON格式
    if python3 -m json.tool "$file" > /dev/null 2>&1; then
        print_success "JSON格式正确"
    else
        print_error "JSON格式错误"
        return 1
    fi

    # 提取版本信息
    local version=$(python3 -c "import json; print(json.load(open('$file'))['latestVersion'])")
    local release_date=$(python3 -c "import json; print(json.load(open('$file'))['releaseDate'])")

    print_info "版本: $version"
    print_info "发布日期: $release_date"

    # 检查必需字段
    local required_fields=("latestVersion" "releaseDate" "releaseNotes" "forceUpdate" "packages")
    for field in "${required_fields[@]}"; do
        if python3 -c "import json; data=json.load(open('$file')); data['$field']" 2>/dev/null; then
            print_success "字段 $field: 存在"
        else
            print_error "字段 $field: 缺失"
            return 1
        fi
    done

    # 检查平台包信息
    local platforms=("windows" "macos" "linux")
    for platform in "${platforms[@]}"; do
        if python3 -c "import json; data=json.load(open('$file')); packages=data['packages']; packages['$platform']" 2>/dev/null; then
            print_success "平台 $platform: 存在"

            # 检查平台包的必需字段
            local package_fields=("url" "size" "hash" "downloadUrl" "minSystemVersion")
            for field in "${package_fields[@]}"; do
                if python3 -c "import json; data=json.load(open('$file')); print(data['packages']['$platform']['$field'])" 2>/dev/null; then
                    local value=$(python3 -c "import json; data=json.load(open('$file')); print(data['packages']['$platform']['$field'])")
                    if [[ "$value" != "待计算" ]]; then
                        print_success "  $platform.$field: $value"
                    else
                        print_warning "  $platform.$field: 待计算"
                    fi
                else
                    print_error "  $platform.$field: 缺失"
                    return 1
                fi
            done
        else
            print_warning "平台 $platform: 不存在"
        fi
    done

    return 0
}

# 启动本地测试服务器
start_local_server() {
    local port=$1
    local directory=$2

    print_info "启动本地测试服务器 (端口: $port)"
    print_info "目录: $directory"

    # 检查端口是否被占用
    if lsof -i :$port >/dev/null 2>&1; then
        print_error "端口 $port 已被占用"
        return 1
    fi

    # 启动HTTP服务器
    cd "$directory"
    python3 -m http.server $port >/dev/null 2>&1 &
    local server_pid=$!

    # 等待服务器启动
    sleep 2

    # 检查服务器是否启动成功
    if lsof -i :$port >/dev/null 2>&1; then
        print_success "测试服务器已启动 (PID: $server_pid)"
        print_info "访问: http://localhost:$port/version.json"

        # 测试访问
        if curl -s "http://localhost:$port/version.json" >/dev/null; then
            print_success "本地服务器可正常访问"
        else
            print_warning "本地服务器访问异常"
        fi

        return 0
    else
        print_error "测试服务器启动失败"
        return 1
    fi
}

# 主函数
main() {
    echo "========================================"
    echo "     本地版本文件测试工具"
    echo "========================================"

    local base_dir="/Users/ethan/Codes/longimagereader/deploy/uploads"

    # 测试LimeReader版本文件
    echo ""
    print_info "测试 LimeReader 版本文件..."
    if test_version_file "$base_dir/limereader/version.json" "LimeReader"; then
        print_success "LimeReader 版本文件测试通过"
    else
        print_error "LimeReader 版本文件测试失败"
    fi

    echo ""
    print_info "测试 LoimReader 版本文件..."
    if test_version_file "$base_dir/loimreader/version.json" "LoimReader"; then
        print_success "LoimReader 版本文件测试通过"
    else
        print_error "LoimReader 版本文件测试失败"
    fi

    echo ""
    print_info "是否启动本地测试服务器? (y/N)"
    read -r response

    if [[ "$response" =~ ^[Yy]$ ]]; then
        echo ""
        print_info "选择要测试的客户端:"
        echo "1) LimeReader"
        echo "2) LoimReader"
        read -p "请选择 (1-2): " choice

        local client_dir=""
        case $choice in
            1)
                client_dir="limereader"
                ;;
            2)
                client_dir="loimreader"
                ;;
            *)
                print_error "无效选择"
                exit 1
                ;;
        esac

        if start_local_server 8080 "$base_dir/$client_dir"; then
            echo ""
            print_info "按任意键停止服务器..."
            read -n 1
            echo ""

            # 停止服务器
            if lsof -ti:8080 | xargs kill 2>/dev/null; then
                print_success "测试服务器已停止"
            fi
        fi
    fi

    echo ""
    print_success "测试完成!"
    echo ""
    print_info "下一步操作:"
    echo "1. 配置ossutil64: ossutil64 config"
    echo "2. 上传版本文件: ./upload_to_oss.sh limereader"
    echo "3. 上传LoimReader: ./upload_to_oss.sh loimreader"
    echo "4. 或上传所有: ./upload_to_oss.sh all"
}

# 运行主函数
main "$@"